<?php

namespace app\common\service;

use app\common\exception\MiException;
use app\common\service\traits\InstanceTrait;
use app\model\store\Goods;
use app\model\store\GoodsSku;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class CommonGoodsService
{
    use InstanceTrait;

    /**
     * 减库存
     * @param Goods $goods
     * @param int $num
     * @param int $skuId
     * @return void
     * @throws MiException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function decStock(Goods $goods, int $num, int $skuId){

        if ($goods->stock < $num) throw new MiException("【{$goods->title}】库存不足");
        // 减库存
        $goods->stock -= $num;
        // 增加销量
        $goods->sales += $num;

        $goods->save();

        // 如果是多规格，对多规格进行处理
        if ($goods->spec_type == 2){    // 多规格
            $sku = GoodsSku::lock(true)->find($skuId);
            if ($sku->stock < $num) throw new MiException("【{$goods->title}】库存不足");
            // 减库存
            $sku->stock -= $num;
            // 增加销量
            $sku->sales += $num;

            $sku->save();
        }

    }

    /**
     * 回滚库存，减少销量
     * @param Goods $goods
     * @param int $num
     * @param int $skuId
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function rollbackStock(Goods $goods, int $num, int $skuId){

        // 回滚库存
        $goods->stock += $num;
        // 减少销量
        $goods->sales -= $num;
        $goods->save();

        // 如果是多规格，对多规格进行处理
        if ($goods->spec_type == 2){    // 多规格
            $sku = GoodsSku::lock(true)->find($skuId);
            // 回滚库存
            $sku->stock += $num;
            // 减少销量
            $sku->sales -= $num;
            $sku->save();
        }

    }
}
